<template>
  <div class="app-container">
    <el-alert show-icon type="warning" title="排班说明" :closable="false">
      <div style="font-size: 14px;">
        第1步:先点击【节假日设置】查看下月排班是否存在节假日调休等情况,如'端午''中秋'等节日<br>
        第2步:点击执行【自动排班】,会自动生产下个月“正常排班”和“值班安排”，用户可以通过APP端打卡界面看见详细排班<br>
        # 已经生成的排班表，可以点击【修改排班】进行手动修改，当前时间之前的不可修改<br>
        # 值班安排会从对应的企业或在编人员名单中轮流安排，员工【离职】或【入职】请及时更新相关人员配置<br>
        # 每次执行自动排班会从【<b style="color: indianred;">执行之日起生成至下个月末</b>】的排班记录，建议每月20日前手动生成下月排班，如果未排班21日会自动执行排班
      </div>

    </el-alert>
    <div style="padding: 10px" />
    <el-button type="success" size="mini" plain @click="showPaibanSettingDialog">排班设置</el-button>

    <el-button type="primary" size="mini" plain @click="openjiejiari">节假日设置</el-button>
    <el-button type="primary" size="mini" plain @click="autoPaiban">执行自动排班</el-button>
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="日期" align="center">
        <template slot-scope="scope">
          {{ scope.row.riqi }}
        </template>
      </el-table-column>
      <el-table-column label="星期" align="center">
        <template slot-scope="scope">
          周{{ ['日','一','二','三','四','五','六'][scope.row.xingqi] }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.typ==1" type="success">休息</el-tag>
          <el-tag v-if="scope.row.typ==0" type="info">上班</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="值班人员" align="center">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.zhiban" :key="index">
            {{ item.name }}&nbsp;
          </span>

        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.typ==1"
            size="mini"
            :type="today(scope.row.riqi)?'info':'primary'"
            plain
            :disabled="today(scope.row.riqi)"
            @click="showAddPaibanDialog(scope.row.id, scope.row.riqi,scope.row.zhiban)"
          >
            {{ today(scope.row.riqi)?'不可修改':'修改值班' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog title="修改值班人员" :visible.sync="addPaibanDialog.visible" width="30%" :close-on-click-modal="false">
      <div>
        <el-form ref="form" label-width="120px" label-position="top">
          <el-form-item label="日期">
            {{ addPaibanDialog.riqi }}
          </el-form-item>
          <el-form-item label="选择值班人">
            <el-select v-model="addPaibanDialog.zhiban" multiple placeholder="请选择" style="width: 100%;" @change="zhibanChange">
              <el-option v-for="item in allUsers" :key="item.uid" :label="item.name" :value="item.uid" />
            </el-select>
            <!-- <el-cascader v-model="addPaibanDialog.zhiban" :options="userList" :props="props" clearable /> -->

          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPaibanDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickAddPaiban()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="值班设置" :visible.sync="paibanSettingDialog.visible" width="50%" :close-on-click-modal="false">
      <div>
        <el-form ref="form" label-width="120px" label-position="top">
          <!-- <h2>已经排班至那天</h2>
          <el-form-item label="">
            <el-date-picker v-model="paibanSettingDialog.nextriqi" type="date" placeholder="选择日期"
              style="width: 100%;" />
          </el-form-item> -->
          <el-row>
            <el-col :span="12">
              <h2>企业人员排班列表</h2>
              <el-form-item label="下次排班从">
                <el-select v-model="paibanSettingDialog.nextqiye" style="width: 80%;">
                  <el-option v-for="item in qiyeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="企业人员">
                <el-checkbox-group v-model="paibanSettingDialog.qiyerenyuan" @change="qiyeChange">
                  <el-checkbox v-for="(item,index) in qiyerenyuan" :key="index" :label="item.uid">{{ item.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <h2>在编人员排班列表</h2>
              <el-form-item label="下次排班从">
                <el-select v-model="paibanSettingDialog.nextzaibian" style="width: 80%;">
                  <el-option v-for="item in zaibianOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="在编人员">
                <el-checkbox-group v-model="paibanSettingDialog.zaibianrenyuan" @change="zaibianChange">
                  <el-checkbox v-for="(item,index) in zaibianrenyuan" :key="index" :label="item.uid">{{ item.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paibanSettingDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="updatePaiban()">设 置</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  websock
} from '@/websock'
import moment from 'moment'

export default {
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      props: {
        multiple: true
      },
      // 人员列表数据
      userList: [],
      allUsers: [],
      paibanSetting: {},
      users: [],
      qiyerenyuan: [],
      qiyeOptions: [],
      zaibianrenyuan: [],
      zaibianOptions: [],
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 30,
      dataTotal: 0,
      // 添加员工
      addPaibanDialog: {
        visible: false,
        id: 0,
        riqi: '',
        zhiban: []
      },
      paibanSettingDialog: {
        visible: false,
        qiyerenyuan: [],
        zaibianrenyuan: [],
        nextqiye: '',
        nextzaibian: '',
        nexttype: '',
        nextriqi: ''
      }
    }
  },
  async created() {
    this.getList()

    websock.getAllUsers().then(res => {
      this.users = res
      for (let i = 0; i != res.length; i++) {
        if (res[i].xingzhi == '企业人员') {
          this.qiyerenyuan.push(res[i])
        } else {
          this.zaibianrenyuan.push(res[i])
        }
      }
      console.log('all users', res)
    })

    const res = await websock.getContactList()
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      // userList.push({
      //   value: i + '',
      //   label: res[i].name,
      //   children: []
      // })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList.push({
          value: JSON.stringify({
            uid: res[i].userList[j].uid,
            name: res[i].userList[j].name,
            avatar: res[i].userList[j].avatar
          }),
          label: res[i].userList[j].name
        })
      }
    }

    this.userList = userList

    this.allUsers = await websock.getAllUsers()
    console.log('all users', this.allUsers)
  },
  methods: {
    today(time) {
      const riqi = moment(time)
      const today = moment()
      if (riqi < today) {
        return true
      }
      return false
    },
    openjiejiari() {
      this.$router.push('/sysManage/jiejiariCon')
    },
    getList() {
      this.listLoading = true
      websock.getXiuxiDayList({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
          for (let i = 0; i != this.list.length; i++) {
            this.list[i].riqi = moment(this.list[i].riqi).format('YYYY-MM-DD')
          }
          console.log('xiuxi days', this.list)
        }
      )
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    // 显示添加员工界面
    showAddPaibanDialog(id, riqi, zhiban) {
      console.log('show add paiban dialog riqi', riqi)
      console.log('show add paiban dialog zhiban', zhiban)
      this.addPaibanDialog.visible = true
      this.addPaibanDialog.riqi = riqi
      this.addPaibanDialog.id = id
      this.addPaibanDialog.zhiban = []

      for (let i = 0; i != zhiban.length; i++) {
        console.log('show add paiban dialog zhiban1', zhiban[i], zhiban[i].name)
        this.addPaibanDialog.zhiban.push(zhiban[i].uid)
      }

      // for (let i = 0; i != this.addPaibanDialog.zhiban.length; i++) {
      //   zhiban.push({
      //     uid: JSON.parse(this.addPaibanDialog.zhiban[i][1]).uid,
      //     name: JSON.parse(this.addPaibanDialog.zhiban[i][1]).name,
      //     avatar: JSON.parse(this.addPaibanDialog.zhiban[i][1]).avatar
      //   })
      // }
      // this.addPaibanDialog.zhiban = zhiban
    },
    // 显示排班设置界面
    async showPaibanSettingDialog() {
      this.paibanSettingDialog.visible = true
      // 获取排班设置
      this.paibanSetting = await websock.getPaibanSetting()
      console.log('paiban setting', this.paibanSetting)

      this.paibanSettingDialog.qiyerenyuan = this.paibanSetting.qiyerenyuan
      this.paibanSettingDialog.zaibianrenyuan = this.paibanSetting.zaibianrenyuan
      this.paibanSettingDialog.nextqiye = this.paibanSetting.nextqiye
      this.paibanSettingDialog.nextzaibian = this.paibanSetting.nextzaibian
      this.paibanSettingDialog.nexttype = this.paibanSetting.nexttype
      this.paibanSettingDialog.nextriqi = this.paibanSetting.nextriqi

      this.qiyeOptions = []
      for (let i = 0; i != this.paibanSetting.qiyerenyuan.length; i++) {
        const value = this.paibanSetting.qiyerenyuan[i]
        let label = value
        for (let j = 0; j != this.users.length; j++) {
          if (this.users[j].uid == value) {
            label = this.users[j].name
            break
          }
        }
        this.qiyeOptions.push({
          value,
          label
        })
      }

      this.zaibianOptions = []
      for (let i = 0; i != this.paibanSetting.zaibianrenyuan.length; i++) {
        const value = this.paibanSetting.zaibianrenyuan[i]
        let label = value
        for (let j = 0; j != this.users.length; j++) {
          if (this.users[j].uid == value) {
            label = this.users[j].name
            break
          }
        }
        this.zaibianOptions.push({
          value,
          label
        })
      }
    },
    // 更新排班
    async updatePaiban() {
      if (this.paibanSettingDialog.nextriqi) {
        this.paibanSettingDialog.nextriqi = moment(this.paibanSettingDialog.nextriqi).format('YYYY-MM-DD')
      }
      await websock.updatePaibanSetting(this.paibanSettingDialog)
      this.paibanSettingDialog.visible = false
    },
    qiyeChange() {
      console.log('qiye change', this.paibanSettingDialog)
      this.qiyeOptions = []
      for (let i = 0; i != this.paibanSettingDialog.qiyerenyuan.length; i++) {
        const value = this.paibanSettingDialog.qiyerenyuan[i]
        let label = value
        for (let j = 0; j != this.users.length; j++) {
          if (this.users[j].uid == value) {
            label = this.users[j].name
            break
          }
        }
        this.qiyeOptions.push({
          value,
          label
        })
      }
    },
    zaibianChange() {
      console.log('zaibian change', this.paibanSettingDialog)
      this.zaibianOptions = []
      for (let i = 0; i != this.paibanSettingDialog.zaibianrenyuan.length; i++) {
        const value = this.paibanSettingDialog.zaibianrenyuan[i]
        let label = ''
        for (let j = 0; j != this.users.length; j++) {
          console.log(this.users[j].uid, value)
          if (this.users[j].uid == value) {
            label = this.users[j].name
            break
          }
        }
        this.zaibianOptions.push({
          value,
          label
        })
      }
    },
    async clickAddPaiban() {
      if (this.addPaibanDialog.zhiban.length == 0) return this.$message.error('请选择值班人')

      const zhiban = []
      for (let i = 0; i != this.addPaibanDialog.zhiban.length; i++) {
        const uid = this.addPaibanDialog.zhiban[i]
        for (let j = 0; j != this.allUsers.length; j++) {
          if (uid == this.allUsers[j].uid) {
            zhiban.push({
              uid,
              name: this.allUsers[j].name,
              avatar: this.allUsers[j].avatar
            })
            break
          }
        }
      }

      try {
        await websock.addPaiban({
          id: this.addPaibanDialog.id,
          riqi: this.addPaibanDialog.riqi,
          zhiban
        })

        this.addPaibanDialog.visible = false

        this.$message.success('修改排班成功')

        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error(err.message || 'error')
      }
    },
    async autoPaiban() {
      try {
        await websock.autoPaiban()
        this.$message.success('自动排班成功')
        this.getList()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async zhibanChange(e) {
      console.log('zhiban change')
      console.log(e)
      console.log(this.addPaibanDialog.zhiban)
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 120px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>
